package com.study.server.codec;

import com.study.server.message.GameMessage;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * Created by meen on 2017/12/4.
 */
public class MessageDecoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        //头长:HEAD(2bytes) + length(int) + cmdId(short)
        int headLen = GameMessage.HEAD.length + Short.SIZE / Byte.SIZE + Integer.SIZE / Byte.SIZE;
        if (in.readableBytes() < headLen) {
            return;
        }
        in.markReaderIndex();
        byte magic1 = in.readByte();
        byte magic2 = in.readByte();
        System.out.println("读出 magic num:" + magic1 + " -- " + magic2);
        if (magic1 != GameMessage.HEAD[0] || magic2 != GameMessage.HEAD[1]) {
            System.out.println("wrong magic numbers!");
            ctx.close();
            return;
        }
        int length = in.readInt();
        System.out.println("读出 数据长度:" + length);
        if (in.readableBytes() < length - 6) {
            in.resetReaderIndex();
            return;
        }
        short cmdId = in.readShort();
        System.out.println("读出 cmd:" + cmdId);
        byte[] bytes = new byte[length - headLen];
        in.readBytes(bytes);
        GameMessage msg = new GameMessage(cmdId, bytes);
        out.add(msg);
    }
}
